package com.hc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hc.action.MapAreaAction;

public class MapAreaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String actionType = req.getParameter("actionType");  
		if("setMapArea".equals(actionType)){
			String area = req.getParameter("dotList");
			if(MapAreaAction.setArea(area)){
				returnJson(req, resp, "true");
			}else{
				returnJson(req, resp, "false");
			}
		}else if("getMapArea".equals(actionType)){
			int areaId = Integer.parseInt(req.getParameter("areaId"));
			getAreaInfo(req, resp, areaId);
		}
	}
	
	private void getAreaInfo(HttpServletRequest req, HttpServletResponse resp, int areaId){
		returnMsg(req, resp, JSON.toJSONString(MapAreaAction.getMapInfo(areaId)));
	}
	
	private void returnJson(HttpServletRequest req, HttpServletResponse resp, String msg){
		JSONObject json = new JSONObject();
		json.put("success", msg);
		returnMsg(req,resp, json.toString());
	}
	
	private void returnMsg(HttpServletRequest req, HttpServletResponse resp,
			String msg) {
		resp.setCharacterEncoding("utf-8");

		PrintWriter w;
		try {
			w = resp.getWriter();
			w.write(msg);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	
	}
	
}
